<template>
  <div class="chat-container">
    <ul class="title">
      <li style="--i:1;">讯</li>
      <li style="--i:2;">飞</li>
      <li style="--i:3;">智</li>
      <li style="--i:4;">能</li>
      <li style="--i:5;">助</li>
      <li style="--i:6;">手</li>
    </ul>
    <div class="chat-messages" ref="chatWindow">
      <div v-for="(item, index) in messages" :key="index" class="chat-history">
        <div class="user-msg" v-if="item.role === 'user'">
          <div class="msg-right">{{ item.content }}</div>
          <img src="../static/userImage.jpg" class="avatar">
        </div>
        <div class="chat-msg" v-if="item.role === 'assistant'">
          <img src="../static/Rob-img.jpg" class="avatar">
          <MdPreview :model-value="item.content" class="msg-left"></MdPreview>
        </div>
      </div>
    </div>

    <div class="input-area">
      <send_input :isSend="loading" @send_message="sendMessage" ref="sendInput"></send_input>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import Send_input from "../components/send-input.vue"
import { MdPreview } from 'md-editor-v3'
import {useCanSendStore} from "@/store/canSend";
const canSendStore = useCanSendStore();

// 引入样式
import 'md-editor-v3/lib/style.css'

// 响应式数据
const messages = reactive([
  { role: 'assistant', content: '您好！我是讯飞星火AI助手，有什么可以帮您的？' }
])
const loading = ref(false)
const chatWindow = ref<HTMLDivElement | null>(null)
const sendInput = ref<InstanceType<typeof Send_input> | null>(null)

// 当前打字机打印的字符位置
const charIndex = ref(0)
// 当前接收到的数据
const currentAns = ref('')
// 判断是否在打印
const isTyping = ref(false)
const typingId = ref<ReturnType<typeof setTimeout> | null>(null)
// 数据是否接收完
const isEnd = ref(false)
// 头像的 URL
const imgUrl = ref('../static/Rob-img.png')
const loadingImg = ref('../static/loading.gif')
console.log(loadingImg.value)
// const showImg = ref(loading? '../static/loading.gif' : '../static/userImage.jpg')

// 防抖滚动到底部
let scrollTimeout: ReturnType<typeof setTimeout> | null = null

const scrollToBottom = () => {
  if (scrollTimeout) clearTimeout(scrollTimeout)

  scrollTimeout = setTimeout(() => {
    if (chatWindow.value) {
      chatWindow.value.scrollTop = chatWindow.value.scrollHeight
    }
  }, 50)
}

// 打字效果
const typeWriterEffect = () => {
  isTyping.value = true
  // canSendStore.setCanSend(false)
  if (charIndex.value < currentAns.value.length) {
    messages[messages.length - 1].content += currentAns.value[charIndex.value]
    charIndex.value++
    scrollToBottom()
    typingId.value = setTimeout(typeWriterEffect, 20)
  } else {
    if (typingId.value !== null) {
      clearTimeout(typingId.value)
      typingId.value = null
    }
    isTyping.value = false

    // 更换头像
    if (isEnd.value) {
      const avatars = document.getElementsByClassName("avatar")
      if (avatars.length > 0) {
        // 断言为 HTMLImageElement 类型
        (avatars[avatars.length - 1] as HTMLImageElement).src = imgUrl.value
      }
      isEnd.value = false
    }
  }
}

// 发送消息处理
const sendMessage = async (userMessage?: string) => {
  const message = userMessage || (sendInput.value ? sendInput.value.message : '')
  charIndex.value=0

  if (!message.trim() || loading.value) {
    return
  }

  // 清除之前的定时器
  if (typingId.value !== null) {
    clearTimeout(typingId.value)
    typingId.value = null
  }

  // 添加用户消息
  messages.push({ role: 'user', content: message })
  if (sendInput.value) {
    sendInput.value.message = ''
  }
  loading.value = true
  scrollToBottom()

  // 添加一个空的 assistant 消息占位符
  const assistantMessage = { role: 'assistant', content: '' }
  // console.log(assistantMessage)
  messages.push(assistantMessage)
  scrollToBottom()

  try {
    await fetchStreamResponse(message, (partialContent) => {
      assistantMessage.content = partialContent
      currentAns.value = partialContent
      // charIndex.value = 0
      typeWriterEffect()
    })
  } catch (error) {
    assistantMessage.content = '抱歉，请求处理时出现错误。请稍后再试。'
  } finally {
    loading.value = false
    isEnd.value = true
    canSendStore.setCanSend(true)
    scrollToBottom()
  }
}

// 讯飞星火大模型API请求（支持流式响应）
const fetchStreamResponse = async (prompt: string, callback: (content: string) => void): Promise<string> => {
  const data = {
    question: prompt,
    userId: 123
  }

  const response = await fetch('http://localhost:8080/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })

  if (!response.ok) {
    throw new Error('网络响应异常')
  }

  const reader = response.body.getReader()
  const decoder = new TextDecoder()
  let aiContent = ''

  while (true) {
    const { done, value } = await reader!.read()
    if (done) break

    const lines = decoder.decode(value, { stream: true })

    for (const content of lines) {
      aiContent += content
    }
    currentAns.value=aiContent
    if (!isTyping.value){
      typeWriterEffect()
    }
    isEnd.value=true
    // messages[messages.length - 1].content = aiContent
  }
  // console.log('ChatGPT:', messages[messages.length - 1].content)
  // useIsEndStore().setIsEnd(true)
  return aiContent
}
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 20px auto;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #f5f7fa;
}

.input-area {
  display: flex;
  gap: 12px;
  padding: 20px;
  background: white;
  border-top: 1px solid #ebeef5;
}

.title li {
  display: inline-block;
  list-style: none;
  animation: shine 2s linear infinite;
  animation-delay: calc(0.1s * var(--i));
}
.chat-messages {
  height: 500px;
  overflow-y: auto;
  padding: 20px;
}
@keyframes shine {
  0% {
    color: white;
    text-shadow: 0 0 10px #00b3ff,
      0 0 20px #00b3ff,
      0 0 40px #00b3ff
  }

  30%,
  70% {
    color: white;
    filter: hue-rotate(360deg);
    text-shadow: 0 0 10px #00b3ff,
      0 0 20px #00b3ff,
      0 0 40px #00b3ff
  }

  100% {
    color: transparent;
    box-shadow: none;

  }
}

.main-body {
  position: relative;
  left: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 980px;
  height: 940px;
  background-color: white;
  margin: 0 auto;
  padding-right: 20px;
  padding-left: 20px;
  margin-left: -510px;
  border: 1.5px solid;
  border-image: linear-gradient(to right, #8f41e9, #578aef) 1;
}

.title {
  padding: 10px;
  font-weight: bolder;
  font-size: 22px;
  color: transparent;

}

.chat-body {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 780px;
  padding: 20px;
  background-color: #F1F2F6;
  overflow: auto;
  scrollbar-width: none;
  /* 对于Firefox */
  -ms-overflow-style: none;
  /* 对于Internet Explorer和Edge */
  border-radius: 15px;
}

.chat-body::-webkit-scrollbar {
  display: none;
}

.user-msg {
  display: flex;
  justify-content: right;
  align-items: flex-start;
  background-color: #F1F2F6;
}

.chat-msg {
  display: flex;
  justify-content: left;
  align-items: flex-start;
  background-color: #F1F2F6;

}

.msg-right {
  font-size: 20px;
  line-height: 28px;
  padding: 10px;
  background-color: aquamarine;
  max-width: 870px;
  margin-left: 8px;
  margin-right: 5px;
  border-radius: 10px;
  margin-bottom: 8px;
}

.msg-left {
  font-size: 20px;
  line-height: 28px;
  padding: 10px;
  background-color: white;
  margin-left: 8px;
  max-width: 870px;
  margin-right: 5px;
  border-radius: 10px;
  margin-bottom: 8px;
  text-align: left;
}

.avatar {
  width: 40px;
  height: 40px;
}

.input-era {
  position: absolute;
  position: relative;
  width: 100%;

}
</style>